<script setup lang="ts">
import { ref } from 'vue'
import type { Marker } from '@/types/guide'

// 定义响应式变量
const location = ref({
  latitude: 40.149009, // 初始纬度
  longitude: 122.933426, // 初始经度
})

// 定义点击状态变量
const isClicked = ref(false)
const mRScale = ref(12.7)
// 获取当前位置
const getLocation = () => {
  uni.getLocation({
    type: 'gcj02', // 获取坐标系位置
    success(res) {
      // 更新位置
      location.value.latitude = res.latitude
      location.value.longitude = res.longitude

      mRScale.value = 20
      console.log('当前位置:', res)
    },
    fail(err) {
      console.error('获取位置失败:', err)
    },
  })
}

// 按钮点击时改变样式
const onButtonClick = () => {
  // 设置按钮点击状态为 true
  isClicked.value = true
  // 调用定位函数
  getLocation()

  // 点击后延时恢复原样
  setTimeout(() => {
    isClicked.value = false
  }, 300) // 300ms后恢复
}

// // 定义区域的坐标 (多边形)
// const polygonCoordinates = [
//   { latitude: 40.153612, longitude: 122.929705 }, // 西北角
//   { latitude: 40.154823, longitude: 122.93567 }, // 北边
//   { latitude: 40.153612, longitude: 122.941635 }, // 东北角
//   { latitude: 40.147647, longitude: 122.94318 }, // 东边
//   { latitude: 40.144014, longitude: 122.941635 }, // 东南角
//   { latitude: 40.142803, longitude: 122.93567 }, // 南边
//   { latitude: 40.144014, longitude: 122.929705 }, // 西南角
//   { latitude: 40.147647, longitude: 122.92816 }, // 西边
//   { latitude: 40.153612, longitude: 122.929705 }, // 闭合回到西北角
// ]

// 修改 markers 的定义，移除天门山标记
const markers = ref<Marker[]>([
  {
    id: 1,
    name: '南门',
    latitude: 40.149509,
    longitude: 122.933926,
    iconPath: '',
    width: 24,
    height: 24,
    joinCluster: true,
    callout: {
      content: '南门',
      display: 'BYCLICK',
      fontSize: 12,
      padding: 8,
      borderRadius: 4,
      bgColor: '#ffffff',
      textAlign: 'center',
    },
  },
  {
    id: 2,
    name: '西门',
    latitude: 40.148509,
    longitude: 122.934426,
    iconPath: '',
    width: 24,
    height: 24,
    joinCluster: true,
    callout: {
      content: '西门',
      display: 'BYCLICK',
      fontSize: 12,
      padding: 8,
      borderRadius: 4,
      bgColor: '#ffffff',
      textAlign: 'center',
    },
  },
  {
    id: 3,
    name: '北门',
    latitude: 40.149009,
    longitude: 122.934926,
    iconPath: '',
    width: 24,
    height: 24,
    joinCluster: true,
    callout: {
      content: '北门',
      display: 'BYCLICK',
      fontSize: 12,
      padding: 8,
      borderRadius: 4,
      bgColor: '#ffffff',
      textAlign: 'center',
    },
  },
])

// 控制地点列表显示状态
const showLocationList = ref(false)

// 移动到选中的地点
const moveToLocation = (marker: Marker) => {
  location.value.latitude = marker.latitude
  location.value.longitude = marker.longitude

  // 更新所有标记的 callout 显示状态
  markers.value = markers.value.map((m) => {
    const newMarker = { ...m }
    newMarker.callout = {
      ...newMarker.callout,
      display: m.id === marker.id ? 'ALWAYS' : 'BYCLICK',
    }
    return newMarker
  })

  mRScale.value = 18
  showLocationList.value = false
}

// 切换地点列表显示状态
const toggleLocationList = () => {
  showLocationList.value = !showLocationList.value
}

const onMapTap = (e: any) => {
  // 获取点击的经纬度
  const { latitude, longitude } = e.detail

  // 计算当前位置和目标位置的差值
  const latDiff = latitude - location.value.latitude
  const lngDiff = longitude - location.value.longitude

  // 设置动画参数
  const duration = 300 // 动画持续时间（毫秒）
  const frames = 30 // 动画帧数
  const interval = duration / frames // 每帧间隔时间
  let currentFrame = 0

  // 创建动画函数
  const animate = () => {
    if (currentFrame >= frames) return

    // 使用缓动函数使移动更自然
    const progress = easeInOutQuad(currentFrame / frames)

    // 更新位置
    location.value.latitude += latDiff * (1 / frames)
    location.value.longitude += lngDiff * (1 / frames)
    currentFrame++
    // 使用 setTimeout 代替 requestAnimationFrame
    setTimeout(animate, interval)
  }

  // 开始动画
  animate()

  // 设置缩放级别
  mRScale.value = 18

  // 更新所有标记的 callout 显示状态为 BYCLICK
  markers.value = markers.value.map((m) => {
    const newMarker = { ...m }
    newMarker.callout = {
      ...newMarker.callout,
      display: 'BYCLICK',
    }
    return newMarker
  })
}

// 缓动函数
const easeInOutQuad = (t: number): number => {
  return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
}
</script>

<template>
  <view>
    <view class="page-body">
      <view class="page-section page-section-gap">
        <!-- 地图组件 -->
        <map
          style="width: 100%; height: 100vh"
          :latitude="location.latitude"
          :longitude="location.longitude"
          :scale="mRScale"
          show-location
          :markers="markers"
          max-scale="20"
          min-scale="12.5"
          enable-cluster
          :cluster-style="{
            color: '#fff',
            fontSize: '12px',
            bgColor: '#1296db',
            borderColor: '#b3e5ff',
            borderWidth: 2,
            borderRadius: '50%',
            padding: '8px',
          }"
          @tap="onMapTap"
        >
        </map>

        <!-- 定位按钮 -->
        <view class="locate-button" :class="{ clicked: isClicked }" @click="onButtonClick">
          <image src="/static/tabs/location.svg" style="width: 30px; height: 30px" />
        </view>

        <!-- 在定位按钮后添加以下代码 -->
        <view
          class="locations-button"
          :class="{ clicked: showLocationList }"
          @click="toggleLocationList"
        >
          <image src="/static/tabs/map.svg" style="width: 30px; height: 30px" />
        </view>

        <!-- 地点列表弹出层 -->
        <view class="location-list" v-if="showLocationList">
          <view
            v-for="marker in markers.filter((m) => m.id !== 0)"
            :key="marker.id"
            class="location-item"
            @click="moveToLocation(marker)"
          >
            {{ marker.name }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.page-body {
  position: relative;
  height: 100vh;
}

.locate-button {
  position: absolute;
  top: 580px;
  right: 20px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease; /* 平滑过渡 */
}

.locate-button.clicked {
  background-color: #e0e0e0; /* 点击时背景颜色变浅 */
}

.locations-button {
  position: absolute;
  top: 500px; // 位置在定位按钮上方
  right: 20px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease;
  z-index: 100;
}

.locations-button.clicked {
  background-color: #e0e0e0;
}

.location-list {
  position: absolute;
  top: 420px;
  right: 80px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  padding: 10px 0;
  z-index: 99;
}

.location-item {
  padding: 10px 20px;
  min-width: 100px;
  text-align: center;

  &:hover {
    background-color: #f5f5f5;
  }

  &:active {
    background-color: #e0e0e0;
  }
}
</style>
